// 常用的工具函数
// 只能在Main process中使用

const { dialog, BrowserWindow, Menu, shell, } = require('electron')
const os = require('os')
const path = require('path')
const url = require('url')
const isDev = require('electron-is-dev')

let currentOpenedModalWindow = [];
let mainWindow = null;  // 主窗口

function openModal({ fileName, perentWindow, width, height, minimizable, resizable, devTools }) {
    let { ...params } = arguments[0];
    params.modal = true;
    params.url = fileName;
    return openUrl(params);
}

function openUrl({ url, perentWindow, modal, width, height, minimizable, resizable, devTools }) {
    let win = new BrowserWindow({
        title: 'Loading...',
        parent: perentWindow || null,
        width: width || 400,
        height: height || 400,
        resizable: resizable ? resizable : false,
        minimizable: minimizable ? minimizable : true,
        modal: modal || false,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            nodeIntegration: true,
            contextIsolation: true,
        }
    });
    win.setMenu(null);
    if (!isDarwin()) {
        win.setIcon(path.join(__dirname, 'favicon.ico'));
    }
    let theUrl = url;
    if (!(/^http/gi.test(url))) {
        theUrl = 'file://' + __dirname + '/' + url;
    }
    win.loadURL(theUrl);
    win.show();
    if (devTools) {
        win.webContents.openDevTools();
    }
    if (modal) {
        currentOpenedModalWindow.push(win);
    }
    return win;
}

function getMenuItemById(items, id) {
    if (items instanceof Menu) {
        items = items.items;
    }
    let found = items.find(item => id === item.id) || false;
    for (let i = 0, length = items.length; !found && i < length; i++) {
        if (items[i].submenu) {
            found = getMenuItemById(items[i].submenu, id);
        }
    }
    return found;
};

function closeModal() {
    let currModalWindow = currentOpenedModalWindow.pop();
    if (currModalWindow) {
        currModalWindow.close();
    }
}

function openLink(link) {
    shell.openExternal(link);
}

function setMainWindow(win) {
    mainWindow = win;
}

function getMainWindow() {
    return mainWindow;
}

function alert({ msg, title, okText }) {
    if (title) {
        dialog.showMessageBox({
            type: 'info',
            buttons: [okText || '确定'],
            title: title,
            message: msg
        }).then(resp => {

        });
    } else {
        mainWindow && mainWindow.webContents.executeJavaScript(`alert('${msg}');`);
    }
}

function error({ msg, title, okText }) {
    dialog.showMessageBox({
        type: 'error',
        buttons: [okText || '确定'],
        title: title || '错误',
        message: msg
    }).then(resp => {

    });
}

function getSystemInformation() {
    return {
        platform: os.platform(),
        arch: os.arch(),
        release: os.release(),
        type: os.type(),
        hostname: os.hostname(),
        uptime: os.uptime(),
        loadavg: os.loadavg(),
        totalmem: os.totalmem(),
        freemem: os.freemem(),
        networkInterfaces: os.networkInterfaces(),
        homedir: os.homedir(),
        tmpdir: os.tmpdir(),
        endianness: os.endianness(),
        cpus: os.cpus()
    }
}

function isDarwin() {
    return os.platform() === 'darwin';
}

module.exports = {
    openModal,
    getMenuItemById,
    isDev,
    closeModal,
    openLink,
    setMainWindow,
    getMainWindow,
    alert,
    error,
    getSystemInformation,
    openUrl,
    isDarwin,
}
